/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import entity.Book;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.HashMap;
import java.util.List;
import util.DatabaseUtil;

public class FindCart {
    public List<Book> findCart(int memberId){     //找到某个用户购物车里未被删除的书
        List<Book> list=new ArrayList<>();
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con=DatabaseUtil.connect();
            ps=con.prepareStatement("select * from book where id in(select bookid from cart where memberid=?) and isdelete=0");
            ps.setInt(1,memberId);
            rs=ps.executeQuery();
            while(rs.next()){
                list.add(new Book(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDate(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getInt(8),rs.getFloat(9),rs.getString(10),rs.getBoolean(11)));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DatabaseUtil.closeConnection(con, ps,null);
        }
        return list;
    }
    
    public int findCartCount(int memberId,int bookId){
        int i=0;
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con=DatabaseUtil.connect();
            ps=con.prepareStatement("select count from cart where bookid=? and memberid=?");
            ps.setInt(1,bookId);
            ps.setInt(2,memberId);
            rs=ps.executeQuery();
            while(rs.next()){
                i=rs.getInt(1);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DatabaseUtil.closeConnection(con, ps,null);
        }
        return i;
    }
    
    public HashMap<Integer,Integer> findAllCart(int memberId){     
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con=DatabaseUtil.connect();
            ps=con.prepareStatement("select * from cart where memberid=?");
            ps.setInt(1,memberId);
            rs=ps.executeQuery();
            while(rs.next()){
                map.put(rs.getInt(1),rs.getInt(3));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DatabaseUtil.closeConnection(con, ps,null);
        }
        return map;
    }
    
}
